/**
 * 库存管理模块
 * 负责商品库存的查看、更新、预警等功能
 */

const inventory = {
    // 库存数据存储
    inventoryData: [],
    
    // 当前页码
    currentPage: 1,
    
    // 每页显示条数
    pageSize: 10,
    
    // 筛选条件
    filters: {
        productName: '',
        category: '',
        lowStockOnly: false,
        status: 'all'
    },
    
    // 初始化库存管理模块
    init: function() {
        console.log('库存管理模块初始化...');
        this.generateMockData();
        this.setupEventListeners();
        this.renderInventoryTable();
        this.updateInventorySummary();
        this.setupLowStockAlerts();
    },
    
    // 生成模拟数据
    generateMockData: function() {
        // 从商品数据中获取商品信息来生成库存数据
        if (window.products && products.productsData) {
            this.inventoryData = products.productsData.map(product => {
                // 为每个商品变体生成库存记录
                return product.variants.map(variant => {
                    const attributesStr = Object.entries(variant.attributes)
                        .map(([key, value]) => `${key}: ${value}`)
                        .join(', ');
                    
                    return {
                        id: `${product.id}-${variant.sku}`,
                        productId: product.id,
                        productName: product.name,
                        sku: variant.sku,
                        attributes: attributesStr,
                        currentStock: variant.stock,
                        safetyStock: Math.floor(variant.stock * 0.3), // 安全库存为当前库存的30%
                        unitCost: (variant.price * 0.7).toFixed(2), // 成本价为售价的70%
                        lastUpdated: this.getRandomDate(),
                        location: this.getRandomLocation(),
                        status: this.getStatusByStock(variant.stock, Math.floor(variant.stock * 0.3)),
                        categories: product.categories
                    };
                });
            }).flat();
        } else {
            // 如果商品数据不可用，生成独立的模拟库存数据
            this.inventoryData = Array.from({length: 50}, (_, index) => {
                const currentStock = Math.floor(Math.random() * 500);
                const safetyStock = Math.floor(currentStock * 0.3);
                
                return {
                    id: `INV-${index + 1000}`,
                    productId: `P-${Math.floor(Math.random() * 1000)}`,
                    productName: `商品 ${index + 1}`,
                    sku: `SKU-${10000 + index}`,
                    attributes: `颜色: ${['红色', '蓝色', '黑色', '白色'][Math.floor(Math.random() * 4)]}, 尺寸: ${['S', 'M', 'L', 'XL'][Math.floor(Math.random() * 4)]}`,
                    currentStock: currentStock,
                    safetyStock: safetyStock,
                    unitCost: (Math.random() * 200 + 50).toFixed(2),
                    lastUpdated: this.getRandomDate(),
                    location: this.getRandomLocation(),
                    status: this.getStatusByStock(currentStock, safetyStock),
                    categories: [['电子产品', '服装', '食品', '家居'][Math.floor(Math.random() * 4)]]
                };
            });
        }
    },
    
    // 获取随机日期
    getRandomDate: function() {
        const now = new Date();
        const past = new Date(now.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000);
        return past.toISOString().split('T')[0];
    },
    
    // 获取随机库位
    getRandomLocation: function() {
        const locations = ['A区', 'B区', 'C区', 'D区', 'E区'];
        const shelves = ['01', '02', '03', '04', '05'];
        const levels = ['1', '2', '3'];
        
        return `${locations[Math.floor(Math.random() * locations.length)]}-${shelves[Math.floor(Math.random() * shelves.length)]}-${levels[Math.floor(Math.random() * levels.length)]}`;
    },
    
    // 根据库存量确定状态
    getStatusByStock: function(currentStock, safetyStock) {
        if (currentStock <= 0) return '缺货';
        if (currentStock <= safetyStock) return '预警';
        if (currentStock <= safetyStock * 2) return '低库存';
        return '正常';
    },
    
    // 设置事件监听器
    setupEventListeners: function() {
        // 搜索框事件
        document.getElementById('inventory-search').addEventListener('input', () => {
            this.filters.productName = document.getElementById('inventory-search').value.toLowerCase();
            this.currentPage = 1;
            this.renderInventoryTable();
        });
        
        // 分类筛选
        document.getElementById('inventory-category').addEventListener('change', () => {
            this.filters.category = document.getElementById('inventory-category').value;
            this.currentPage = 1;
            this.renderInventoryTable();
        });
        
        // 低库存筛选
        document.getElementById('low-stock-filter').addEventListener('change', () => {
            this.filters.lowStockOnly = document.getElementById('low-stock-filter').checked;
            this.currentPage = 1;
            this.renderInventoryTable();
        });
        
        // 状态筛选
        document.getElementById('inventory-status').addEventListener('change', () => {
            this.filters.status = document.getElementById('inventory-status').value;
            this.currentPage = 1;
            this.renderInventoryTable();
        });
        
        // 导出按钮事件
        document.getElementById('export-inventory').addEventListener('click', () => {
            this.exportInventoryData();
        });
        
        // 刷新按钮事件
        document.getElementById('refresh-inventory').addEventListener('click', () => {
            this.refreshInventory();
        });
    },
    
    // 过滤库存数据
    getFilteredData: function() {
        return this.inventoryData.filter(item => {
            // 商品名称筛选
            const matchesName = item.productName.toLowerCase().includes(this.filters.productName);
            
            // 分类筛选
            const matchesCategory = !this.filters.category || item.categories.includes(this.filters.category);
            
            // 低库存筛选
            const matchesLowStock = !this.filters.lowStockOnly || item.status === '预警' || item.status === '低库存' || item.status === '缺货';
            
            // 状态筛选
            const matchesStatus = this.filters.status === 'all' || item.status === this.filters.status;
            
            return matchesName && matchesCategory && matchesLowStock && matchesStatus;
        });
    },
    
    // 渲染库存表格
    renderInventoryTable: function() {
        const filteredData = this.getFilteredData();
        const tableBody = document.getElementById('inventory-table-body');
        tableBody.innerHTML = '';
        
        // 计算分页
        const totalPages = Math.ceil(filteredData.length / this.pageSize);
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = Math.min(startIndex + this.pageSize, filteredData.length);
        const currentData = filteredData.slice(startIndex, endIndex);
        
        // 渲染表格内容
        currentData.forEach(item => {
            const row = document.createElement('tr');
            
            // 根据库存状态设置行样式
            let statusClass = '';
            switch(item.status) {
                case '正常': statusClass = 'status-normal'; break;
                case '低库存': statusClass = 'status-low'; break;
                case '预警': statusClass = 'status-warning'; break;
                case '缺货': statusClass = 'status-out'; break;
            }
            
            row.className = statusClass;
            
            row.innerHTML = `
                <td>${item.productName}</td>
                <td>${item.sku}</td>
                <td>${item.attributes}</td>
                <td class="stock-quantity">${item.currentStock}</td>
                <td>${item.safetyStock}</td>
                <td>¥${item.unitCost}</td>
                <td>${item.location}</td>
                <td>${item.lastUpdated}</td>
                <td>
                    <span class="badge ${this.getStatusBadgeClass(item.status)}">${item.status}</span>
                </td>
                <td>
                    <button class="btn btn-secondary btn-sm" onclick="inventory.viewInventoryDetails('${item.id}')">详情</button>
                    <button class="btn btn-primary btn-sm" onclick="inventory.openAdjustModal('${item.id}')">调整</button>
                </td>
            `;
            
            tableBody.appendChild(row);
        });
        
        // 更新分页控件
        this.renderPagination(filteredData.length, totalPages);
        
        // 更新结果统计
        document.getElementById('inventory-count').textContent = filteredData.length;
    },
    
    // 获取状态徽章样式类
    getStatusBadgeClass: function(status) {
        switch(status) {
            case '正常': return 'badge-success';
            case '低库存': return 'badge-warning';
            case '预警': return 'badge-danger';
            case '缺货': return 'badge-secondary';
            default: return 'badge-info';
        }
    },
    
    // 渲染分页控件
    renderPagination: function(totalItems, totalPages) {
        const paginationContainer = document.getElementById('inventory-pagination');
        paginationContainer.innerHTML = '';
        
        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = this.currentPage === 1;
        prevButton.addEventListener('click', () => {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.renderInventoryTable();
            }
        });
        paginationContainer.appendChild(prevButton);
        
        // 页码按钮
        const maxButtons = 5;
        let startPage = Math.max(1, this.currentPage - Math.floor(maxButtons / 2));
        let endPage = Math.min(totalPages, startPage + maxButtons - 1);
        
        if (endPage - startPage + 1 < maxButtons) {
            startPage = Math.max(1, endPage - maxButtons + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageButton = document.createElement('button');
            pageButton.textContent = i;
            pageButton.className = i === this.currentPage ? 'active' : '';
            pageButton.addEventListener('click', () => {
                this.currentPage = i;
                this.renderInventoryTable();
            });
            paginationContainer.appendChild(pageButton);
        }
        
        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = this.currentPage === totalPages;
        nextButton.addEventListener('click', () => {
            if (this.currentPage < totalPages) {
                this.currentPage++;
                this.renderInventoryTable();
            }
        });
        paginationContainer.appendChild(nextButton);
    },
    
    // 更新库存摘要统计
    updateInventorySummary: function() {
        const totalItems = this.inventoryData.length;
        const lowStockItems = this.inventoryData.filter(item => 
            item.status === '预警' || item.status === '低库存'
        ).length;
        const outOfStockItems = this.inventoryData.filter(item => item.status === '缺货').length;
        const totalValue = this.inventoryData.reduce((sum, item) => 
            sum + (item.currentStock * parseFloat(item.unitCost)), 0
        );
        
        document.getElementById('total-inventory-items').textContent = totalItems;
        document.getElementById('low-stock-items').textContent = lowStockItems;
        document.getElementById('out-of-stock-items').textContent = outOfStockItems;
        document.getElementById('inventory-total-value').textContent = totalValue.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
    },
    
    // 设置低库存警报
    setupLowStockAlerts: function() {
        const alertsContainer = document.getElementById('low-stock-alerts');
        alertsContainer.innerHTML = '';
        
        const alertItems = this.inventoryData.filter(item => 
            item.status === '预警' || item.status === '缺货'
        ).slice(0, 5); // 只显示前5个警报
        
        if (alertItems.length === 0) {
            alertsContainer.innerHTML = '<p class="text-center text-muted">暂无库存警报</p>';
            return;
        }
        
        alertItems.forEach(item => {
            const alertCard = document.createElement('div');
            alertCard.className = 'alert-card';
            alertCard.innerHTML = `
                <div class="alert-content">
                    <h4>${item.productName}</h4>
                    <p>${item.sku} | ${item.attributes}</p>
                    <div class="alert-stock-info">
                        <span>当前库存: ${item.currentStock}</span>
                        <span class="alert-stock-level">${item.status}</span>
                    </div>
                </div>
                <button class="btn btn-primary btn-sm" onclick="inventory.openAdjustModal('${item.id}')">补货</button>
            `;
            alertsContainer.appendChild(alertCard);
        });
    },
    
    // 查看库存详情
    viewInventoryDetails: function(id) {
        const item = this.inventoryData.find(item => item.id === id);
        if (!item) return;
        
        // 构建详情内容
        const detailsContent = `
            <div class="detail-item">
                <strong>商品名称:</strong> ${item.productName}
            </div>
            <div class="detail-item">
                <strong>SKU:</strong> ${item.sku}
            </div>
            <div class="detail-item">
                <strong>属性:</strong> ${item.attributes}
            </div>
            <div class="detail-item">
                <strong>当前库存:</strong> ${item.currentStock}
            </div>
            <div class="detail-item">
                <strong>安全库存:</strong> ${item.safetyStock}
            </div>
            <div class="detail-item">
                <strong>单位成本:</strong> ¥${item.unitCost}
            </div>
            <div class="detail-item">
                <strong>库存价值:</strong> ¥${(item.currentStock * parseFloat(item.unitCost)).toFixed(2)}
            </div>
            <div class="detail-item">
                <strong>库位:</strong> ${item.location}
            </div>
            <div class="detail-item">
                <strong>最后更新:</strong> ${item.lastUpdated}
            </div>
            <div class="detail-item">
                <strong>状态:</strong> <span class="badge ${this.getStatusBadgeClass(item.status)}">${item.status}</span>
            </div>
        `;
        
        // 显示详情模态框
        this.showModal('库存详情', detailsContent);
    },
    
    // 打开库存调整模态框
    openAdjustModal: function(id) {
        const item = this.inventoryData.find(item => item.id === id);
        if (!item) return;
        
        const modalContent = `
            <div class="form-group">
                <label class="form-label">商品名称</label>
                <input type="text" class="form-control" value="${item.productName}" disabled>
            </div>
            <div class="form-group">
                <label class="form-label">SKU</label>
                <input type="text" class="form-control" value="${item.sku}" disabled>
            </div>
            <div class="form-group">
                <label class="form-label">当前库存</label>
                <input type="text" class="form-control" value="${item.currentStock}" disabled>
            </div>
            <div class="form-group">
                <label class="form-label">调整类型</label>
                <select id="adjust-type" class="form-select">
                    <option value="increase">增加库存</option>
                    <option value="decrease">减少库存</option>
                    <option value="set">设置为</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">调整数量</label>
                <input type="number" id="adjust-quantity" class="form-control" min="1">
            </div>
            <div class="form-group">
                <label class="form-label">调整原因</label>
                <textarea id="adjust-reason" class="form-control" rows="3"></textarea>
            </div>
        `;
        
        // 显示模态框并设置确认按钮动作
        this.showModal('调整库存', modalContent, () => {
            const adjustType = document.getElementById('adjust-type').value;
            const quantity = parseInt(document.getElementById('adjust-quantity').value);
            const reason = document.getElementById('adjust-reason').value;
            
            if (isNaN(quantity) || quantity < 1) {
                alert('请输入有效的调整数量');
                return;
            }
            
            this.adjustInventory(id, adjustType, quantity, reason);
        });
    },
    
    // 调整库存
    adjustInventory: function(id, type, quantity, reason) {
        const item = this.inventoryData.find(item => item.id === id);
        if (!item) return;
        
        // 根据调整类型更新库存
        switch(type) {
            case 'increase':
                item.currentStock += quantity;
                break;
            case 'decrease':
                item.currentStock = Math.max(0, item.currentStock - quantity);
                break;
            case 'set':
                item.currentStock = Math.max(0, quantity);
                break;
        }
        
        // 更新状态和最后更新时间
        item.status = this.getStatusByStock(item.currentStock, item.safetyStock);
        item.lastUpdated = new Date().toISOString().split('T')[0];
        
        // 记录操作日志（这里只是模拟）
        console.log(`库存调整: ${item.productName} (${item.sku}), 类型: ${type}, 数量: ${quantity}, 原因: ${reason}`);
        
        // 重新渲染页面
        this.renderInventoryTable();
        this.updateInventorySummary();
        this.setupLowStockAlerts();
        
        // 显示成功提示
        this.showNotification('库存调整成功', 'success');
    },
    
    // 刷新库存数据
    refreshInventory: function() {
        // 模拟数据更新
        this.inventoryData.forEach(item => {
            // 随机调整一些库存数量
            if (Math.random() > 0.7) {
                const change = Math.floor(Math.random() * 20) - 10; // -10 到 +10 的随机变化
                item.currentStock = Math.max(0, item.currentStock + change);
                item.status = this.getStatusByStock(item.currentStock, item.safetyStock);
                item.lastUpdated = new Date().toISOString().split('T')[0];
            }
        });
        
        // 重新渲染页面
        this.renderInventoryTable();
        this.updateInventorySummary();
        this.setupLowStockAlerts();
        
        // 显示成功提示
        this.showNotification('库存数据已刷新', 'success');
    },
    
    // 导出库存数据
    exportInventoryData: function() {
        const filteredData = this.getFilteredData();
        
        // 准备CSV数据
        const headers = ['商品名称', 'SKU', '属性', '当前库存', '安全库存', '单位成本', '库位', '最后更新', '状态'];
        const csvContent = [
            headers.join(','), // 表头
            ...filteredData.map(item => [
                `"${item.productName}"`,
                `"${item.sku}"`,
                `"${item.attributes}"`,
                item.currentStock,
                item.safetyStock,
                item.unitCost,
                `"${item.location}"`,
                item.lastUpdated,
                `"${item.status}"`
            ].join(','))
        ].join('\n');
        
        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `库存数据_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 显示成功提示
        this.showNotification('库存数据导出成功', 'success');
    },
    
    // 显示模态框
    showModal: function(title, content, confirmCallback) {
        // 创建模态框元素（如果不存在）
        let modal = document.getElementById('inventory-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'inventory-modal';
            modal.className = 'modal';
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="inventory-modal-title"></h3>
                        <button class="modal-close" onclick="document.getElementById('inventory-modal').classList.remove('active')">&times;</button>
                    </div>
                    <div class="modal-body" id="inventory-modal-body"></div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" onclick="document.getElementById('inventory-modal').classList.remove('active')">取消</button>
                        <button class="btn btn-primary" id="inventory-modal-confirm">确认</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
        
        // 设置模态框内容
        document.getElementById('inventory-modal-title').textContent = title;
        document.getElementById('inventory-modal-body').innerHTML = content;
        
        // 设置确认按钮事件
        const confirmButton = document.getElementById('inventory-modal-confirm');
        confirmButton.onclick = () => {
            if (confirmCallback) {
                confirmCallback();
            }
            modal.classList.remove('active');
        };
        
        // 显示模态框
        modal.classList.add('active');
    },
    
    // 显示通知
    showNotification: function(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'success' ? '#2ecc71' : type === 'error' ? '#e74c3c' : '#3498db'};
            color: white;
            padding: 15px 25px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        
        document.body.appendChild(notification);
        
        // 显示通知
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 10);
        
        // 3秒后隐藏通知
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
};

// 当DOM加载完成后初始化库存管理模块
document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('inventory-view')) {
        inventory.init();
    }
});